// pages/goods/detail/index.js
import { reqGoodsInfo } from '@/api/goods'
import { userBehavior } from '@/behaviors/userBehavior'
import { reqAddCart, reqCartList } from '@/api/cart'
import '@/utils/extendApi'

Page({
  behaviors: [ userBehavior ],
  /**
   * 页面的初始数据
   */
  data: {
    goodsInfo:{},
    show: false, // 加入购物车和立即购买时显示的弹框
    count: 1, // 商品购买数量，默认是 1
    blessing: '', // 祝福语
    allCount: '',
    buyNow: 0 // 0是加入购物车，1是立即购买
  },

  // 加入购物车
  handleAddcart() {
    this.setData({
      show: true,
      buyNow: 0
    })
  },

  // 立即购买
  handeGotoBuy() {
    this.setData({
      show: true,
      buyNow: 1
    })
  },

  // 点击关闭弹框时触发的回调
  onClose() {
    this.setData({ show: false })
  },

  // 监听是否更改了购买数量
  onChangeGoodsCount(event) {
    //console.log(event.detail)
    this.setData({
      count:Number(event.detail)
    })
  },

  // 弹框的确定按钮
  async handleSubmit() {
    const { token, count, blessing, buyNow } = this.data
    const goodsId = this.goodsId
    if(!token){
      wx.navigateTo({
        url: '/pages/login/longin',
      })
      return
    }
    //
    if(buyNow === 0){
      const res = await reqAddCart({goodsId, count, blessing})
      if(res.code === 200){
        wx.toast({title: '加入购物车成功'})
        this.getCartCount()
        this.setData({show: false})
      }
    }else{
      wx.navigateTo({
        url: `/modules/orderPayModule/pages/order/detail/detail?goodsId=${goodsId}&blessing=${blessing}`
      })
    }
  },
  async getGoodsInfo(){
    const {data: goodsInfo} = await reqGoodsInfo(this.goodsId)
    this.setData({
      goodsInfo
    })
  },
  async getCartCount(){
    if(!this.data.token){
      return
    }
    const res = await reqCartList()
     if(res.data.length !== 0){
       let allCount = 0
       res.data.forEach( (item) =>{
         allCount += item.count
       })
       this.setData({
         //info属性的属性值要求是字符串类型
         //而且如果购买的数量大于99，页面上需要展示99+
         allCount: allCount>99 ? '99+' : `${allCount}`
       })
     }
  },
  onLoad(options){
    this.goodsId = options.goodsId
    this.getGoodsInfo()
    this.getCartCount()
  },
  previewImage(){
    wx.previewImage({
      urls: this.data.goodsInfo.detailList,
    })
  }
})
